import { DaHuaICCBaseService } from "./base";
import { dahua } from "./type";

export class EventService extends DaHuaICCBaseService {
	/** 订阅事件
	 * - https://open-icc.dahuatech.com/#/home?url=%3Fnav%3Dwiki%2Fevo-event%2Fsubscribe.html&version=enterprisebase/5.0.15&blank=true
	 */
	async subscribe(config: dahua.icc.event.ISubscribeRequest) {
		const url = `${this.config.baseUrl}/evo-apigw/evo-event/1.0.0/subscribe/mqinfo`;
		const res = await this.curl<dahua.icc.IResponse<void>>(url, {
			method: "post",
			headers: {
				Authorization: `bearer ${this.accessToken}`,
			},
			contentType: "json",
			dataType: "json",
			data: config,
		});
		this.handleResponseException(res);
		return res.data.success;
	}

	/** 查询订阅列表 */
	async getSubscribeList(category = "alarm") {
		const token = this.accessToken;
		const url = `${this.config.baseUrl}/evo-apigw/evo-event/1.0.0/subscribe/subscribe-list?monitorType=url&category=${category}`;
		const res = await this.curl<dahua.icc.IResponse<dahua.icc.SubscribeEventListResponse>>(url, {
			headers: {
				Authorization: `bearer ${token}`,
			},
			method: "get",
			contentType: "json",
			dataType: "json",
		});
		this.handleResponseException(res);
		return res.data.data;
	}

	/** 订阅门禁的事件 */
	async subscribeAccessEvent(monitorUrl: string, types: string[]) {
		const url = new URL(monitorUrl);
		const obj: dahua.icc.event.ISubscribeRequest = {
			param: {
				monitors: [
					{
						monitor: monitorUrl,
						monitorType: "url",
						events: [
							{
								category: "alarm",
								subscribeAll: 1,
								domainSubscribe: 2,
								authorities: [
									{
										types: [...types],
									},
								],
							},
						],
					},
				],
				subsystem: {
					subsystemType: 0, //固定值：0
					name: url.hostname.replace(/:/g, "_") + "_alarm", // 替换域名中的 - 为 _
					magic: url.hostname.replace(/:/g, "_"),
				},
			},
		};
		return await this.subscribe(obj);
	}
}
